const Router = require("koa-router");
const router = new Router();
const db = require("../db");

router.post("/api/add/collection", async (ctx, next) => { //添加收藏
    let { userid, productid } = ctx.request.body;

    let data = await db.select(`select * from collectlist where userid="${userid}" and productid="${productid}"`);

    if (data.length != 0) {
        let delResult = await db.del(`delete from collectlist where userid="${userid}" and productid="${productid}"`);
        if (delResult == 0) {
            ctx.body = {
                code: 2,
                msg: "取消成功"
            }
        } else {
            ctx.body = {
                code: 3,
                msg: "取消失败"
            }
        }

        return;
    }

    let findData = await db.select(`select * from productlist where id="${productid}"`);
    let { imgurl, title, price } = findData[0];

    let addResult = await db.add(`insert into collectlist (productid,title,price,userid,imgurl) values (${productid},"${title}","${price}",${userid},"${imgurl}")`);

    if (addResult == 0) {
        ctx.body = {
            code: 0,
            msg: "收藏成功"
        }
    } else {
        ctx.body = {
            code: 1,
            msg: "收藏失败"
        }
    }
})


router.get("/api/isLike", async (ctx, next) => { //查询是否收藏
    let { userid, productid } = ctx.query;
    let data = await db.select(`select * from collectlist where userid="${userid}" and productid="${productid}"`);
    if (data.length != 0) {
        ctx.body = {
            code: 0,
            msg: "已经收藏"
        }
    } else {
        ctx.body = {
            code: 1,
            msg: "未收藏"
        }
    }

})

router.get("/api/collectlist/:id", async (ctx, next) => {
    let { id } = ctx.params;
    let data = await db.select(`select * from collectlist where userid=${id}`);
    ctx.body = data;
})


router.get("/api/del/collection", async (ctx, next) => {
    let { ids } = ctx.query;

    let res = await db.del(`delete from collectlist where id in (${ids})`);
    if (res == 0) {
        ctx.body = {
            code: 0,
            msg: "删除成功"
        }
    } else {
        ctx.body = {
            code: 1,
            msg: "删除失败"
        }
    }
})


module.exports = router;